<template>
  <div class="home">
    <el-row :gutter="20" v-if="userRole === 'ADMIN'">
      <el-col :span="6">
        <el-card class="stat-card">
          <el-statistic title="用户总数" :value="statsTotal" />
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <el-statistic title="管理员数量" :value="statsAdmin" />
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <el-statistic title="普通用户数量" :value="statsNormal" />
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <el-statistic title="已删除用户数量" :value="statsDeleted" />
        </el-card>
      </el-col>
    </el-row>

    <el-card class="recent-students-card">
      <template #header>
        <div class="card-header">
          <span>用户信息</span>
          <el-button class="button" text type="primary" @click="refreshUserList">
            <el-icon><Refresh /></el-icon>
            查看全部
          </el-button>
        </div>
      </template>
      
      <el-table :data="userList" style="width: 100%">
        <el-table-column prop="id" label="用户ID" width="100" />
        <el-table-column prop="username" label="账号" width="120" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="role" label="角色" width="100" />
        <el-table-column prop="avatar" label="头像" width="80">
          <template #default="scope">
            <el-avatar :src="scope.row.avatar" :size="32" />
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <el-card class="quick-actions-card">
      <template #header>
        <span>快捷操作</span>
      </template>
      <div class="quick-actions">
        <el-button type="primary" @click="refreshUserList">
          <el-icon><Refresh /></el-icon>
          刷新用户列表
        </el-button>
      </div>
    </el-card>


  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import { userApi } from '@/api/user'

export default {
  name: 'Home',
  components: { Refresh },
  setup() {
    const userList = ref([])

    // 统计数据（来自后端接口）
    const statsTotal = ref(0)
    const statsAdmin = ref(0)
    const statsNormal = ref(0)
    const statsDeleted = ref(0)
    
    // 获取用户角色
    const userRole = computed(() => {
      const userInfo = localStorage.getItem('userInfo')
      if (userInfo) {
        try {
          const user = JSON.parse(userInfo)
          return user.role || 'USER'
        } catch (e) {
          return 'USER'
        }
      }
      return 'USER'
    })

    const loadUserList = async () => {
      try {
        // 使用封装的API，自动携带token并处理返回结构
        const res = await userApi.getUserList()
        const users = res.data?.list || res.data || []
        userList.value = users
      } catch (error) {
        // 如果失败，回退到localStorage单用户显示
        const userInfo = localStorage.getItem('userInfo')
        if (userInfo) {
          try {
            const user = JSON.parse(userInfo)
            userList.value = [user]
          } catch (e) {
            ElMessage.error('解析用户信息失败')
          }
        }
        ElMessage.error('加载用户信息失败：' + (error.message || '未知错误'))
      }
    }

    const loadStats = async () => {
      try {
        const res = await userApi.getUserStats()
        const data = res.data || res
        statsTotal.value = data.total || 0
        statsAdmin.value = data.admins || 0
        statsNormal.value = data.normals || 0
        statsDeleted.value = data.deleted || 0
      } catch (error) {
        ElMessage.error('加载统计信息失败：' + (error.message || '未知错误'))
      }
    }

    const refreshUserList = async () => {
      await loadUserList()
      await loadStats()
      ElMessage.success('用户列表与统计已刷新')
    }

    onMounted(() => {
      loadUserList()
      loadStats()
    })

    return {
      userList,
      statsTotal,
      statsAdmin,
      statsNormal,
      statsDeleted,
      userRole,
      refreshUserList
    }
  }
}
</script>

<style scoped>
.home {
  padding: 20px;
}

.stat-card {
  text-align: center;
  margin-bottom: 20px;
}

.recent-students-card {
  margin-top: 20px;
}

.quick-actions-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.quick-actions {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
}

.quick-actions .el-button {
  display: flex;
  align-items: center;
  gap: 5px;
}
</style>